/*
 * @Author: deng da chao
 * @Date: 2022-05-24 09:12:11
 * @LastEditTime: 2023-06-12 10:18:55
 * @Description: 请求拦截
 */
import Vue from 'vue';
import axios from 'axios-miniprogram'
import qs from 'qs'
import $store from '@/store/index';
import $functions from '@/utils/functions'

import {
	getToken,
	getRuntimeEnvironment
} from "@/utils/storage";

const http = axios
//服务器域名配置
http.defaults.baseURL = `https://pre-photo-h5.qszzwb3.com/photo/api/v1`;
http.defaults.headers = {
	'content-Type': 'application/json'
}

const CancelToken = axios.CancelToken;
let cancel;
http.defaults.cancelToken = new CancelToken((c) => {
	cancel = c;
})

http.defaults.timeout = 120000; // 设置axios的请求时间  如果超过时间服务端未响应,则取消请求 (canceled)
http.interceptors.request.use(
	async config => {

			config.cancelToken = new CancelToken(function executor(c) {
				// executor 函数接收一个 cancel 函数作为参数
				cancel = c;
			})

			// 发送之前操作config
			if (config.method === 'get') {
				// 如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
				config.paramsSerializer = function(params) {
					return qs.stringify(params, {
						arrayFormat: 'indices'
					})
				}
			}
			// 组装请求头 携带token
			let token = getToken();
			config.headers['Authorization'] = 'Bearer ' + token;
			config.headers['platform'] = 'wx';
			return config;
		},
		err => {
			// 处理错误
			return Promise.reject(err)
		}
)

/**
 * 响应拦截
 */
http.interceptors.response.use(
	response => {
		const res = response.data;
		if (res.code !== 0) {
			if (res.code == 10040) { //token过期
				let title = res.message;
				if (!$store.getters['user/getToken']) {
					title = '登录已过期'
				}
				$functions.error(title)
				// app退出登录
				$functions.goLogin()
			} else {
				if (res.code != '110024' && res.code != '10053') {
					$functions.error(res.message || '活动太火爆了，请重试')
				}
			}
			return Promise.reject(res)
		} else {
			$functions.closeWaiting()
			return Promise.resolve(res)
		}
	},
	err => {
		$functions.closeWaiting();
		console.log('报错信息:', err)
		if (err && err.message == 'app请求') {
			return Promise.reject(err);
		}

		$functions.error(err?.response?.data.message || '活动太火爆了，请重试!')
		return Promise.reject(err);

	}
)

export default http